/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.ncsu.csc.sensors;

import com.sun.spot.peripheral.TimeoutException;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.peripheral.external.ExternalBoard;
import com.sun.spot.sensorboard.EDemoController;

/**
 *
 * @author Richard Pospesel
 */
public class UARTInterface
{
	private static EDemoBoard board = null;
	private static EDemoController controller = null;
	public static void initialize()
	{
			if(board == null)
			{
				board = EDemoBoard.getInstance();
				controller = board.getEDemoController();
				controller.initUART(EDemoBoard.SERIAL_SPEED_2400, EDemoBoard.SERIAL_DATABITS_8, EDemoBoard.SERIAL_PARITY_NONE, EDemoBoard.SERIAL_STOPBITS_1);
			}
	}
	
	public static synchronized void send_byte_array(byte[] array)
	{
		for(int k = 0; k < array.length; k++)
			controller.writeUART(array[k]);
	}

	public static synchronized byte[] receive_byte_array(int count) {
		try
		{
			return receive_byte_array(count, 0L);
		}
		catch(TimeoutException te)
		{
			return new byte[count];
		}
	}
	
	public static synchronized byte[] receive_byte_array(int count, long timeout) throws TimeoutException
	{
		try
		{
			byte[] result = new byte[count];
			for(int k = 0; k < count; k++)
				result[k] = controller.readUART(timeout);
			return result;
		}
		catch (TimeoutException te) {
			te.printStackTrace();
			throw te;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
